package com;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer88 {
    public static void main(String[] args) {
        int port = 502; // 监听的端口号
        ServerSocket serverSocket;

        try {
            // 创建ServerSocket并绑定到2001端口
            serverSocket = new ServerSocket(port);
            System.out.println("88服务器已启动，正在监听端口：" + port);

            while (true) { // 一直监听客户端连接
                // 接受客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接：" + clientSocket.getInetAddress().getHostAddress());

                // 为每个客户端创建一个线程来处理请求
                Thread clientThread = new Thread(new ClientHandler77(clientSocket));
                clientThread.start();
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}

// 客户端处理类
class ClientHandler88 implements Runnable {
    private Socket clientSocket;

    public ClientHandler88(Socket socket) {
        this.clientSocket = socket;
    }

    @Override
    public void run() {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {

            String inputLine;
            while ((inputLine = in.readLine()) != null) { // 读取客户端发送的数据
                System.out.println("客户端消息：" + inputLine);
                out.println("服务器已收到你的消息：" + inputLine); // 向客户端发送响应
            }
        } catch (IOException e) {
            System.err.println("客户端处理失败：" + e.getMessage());
        } finally {
            try {
                clientSocket.close(); // 关闭客户端连接
            } catch (IOException e) {
                System.err.println("关闭客户端连接失败：" + e.getMessage());
            }
        }
    }
}
